package com.egg.common.translate.config;


import com.egg.common.translate.CustomLocaleResolver;
import com.egg.common.translate.util.I18nUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.util.ResourceUtils;
import org.springframework.web.servlet.LocaleResolver;

import java.nio.charset.StandardCharsets;


/**
 * 语言翻译
 */
@Slf4j
@Data
@Configuration
public class I18nConfig {


    /**
     * 设置缓存加载的属性文件的毫秒数
     */
    private static final Long CACHE_MILLIS = 30L * 1000L;


    @Bean
    public LocaleResolver localeResolver() {
        return new CustomLocaleResolver();
    }

    @Bean
    public ReloadableResourceBundleMessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename(ResourceUtils.FILE_URL_PREFIX + I18nFileConfig.getDirectoryPath());
        messageSource.setDefaultEncoding(StandardCharsets.UTF_8.name());
        messageSource.setCacheMillis(CACHE_MILLIS);
        return messageSource;
    }

    /**
     * 初始化 工具类
     *
     * @param messageSource
     * @return
     */
    @Bean
    I18nUtil initI18nUtil(ReloadableResourceBundleMessageSource messageSource) {
        if (null == messageSource) {
            log.error("初始化失败 {} 原因 {}", I18nUtil.class.getName(), ReloadableResourceBundleMessageSource.class.getName() + "为null");
            return new I18nUtil();
        }
        I18nUtil i18nUtil = new I18nUtil();
        i18nUtil.setMessageSource(messageSource);
        log.info("初始化成功 {}", I18nUtil.class.getName());
        return i18nUtil;
    }


}
